//基于vue-auto-routes-webpack-plugin 1.0.10版本修改
//路径生成规则自定义
//子路由规则自定义
const VueAutoRouteWebpackPlugin = require('vue-auto-routes-webpack-plugin')
const fs = require('fs')
/**
 * 路由地址生成规则：
 * views/system/UserList.vue => /system/user-list
 * views/system/List.vue => /system/list
 * views/List.vue => /list
 * views/MainList.vue => /main/list
 * views/user/UserList.vue => /user/list
 * 子路由：子路由内添加 parentName
 * @param path
 * @returns {string}
 */
function generateNewPath(path) {
    var result = '';
    var first = true;
    var preChar = '';
    //将大写字母转为-
    for(var char of path) {
        if(char == '/') {
            first = true;
        }
        if(/[A-Z]/.test(char)){
            if(!first) {
                result+='-'
            }
            result+=char.toLowerCase();
            if(preChar == '/') {
                first = false;
            }
        } else {
            result+=char;
        }
        preChar = char;
    }
    var segArray = result.split("/");
    if(segArray.length>=2) {
        var lastStr = segArray[segArray.length-1];
        var preStr = segArray[segArray.length-2];
        if(lastStr.indexOf(preStr+'-')==0) {
            segArray[segArray.length-1] = lastStr.substring(preStr.length+1,lastStr.length);
            var temp = '';
            for(var str of segArray) {
                if(str=='') {
                    continue;
                }
                temp+='/'+str;
            }
            if(result.charAt(0)!='/') {
                temp = temp.substring(1,temp.length);
            }
            if(result.charAt(result.length-1) == '/') {
                temp+='/';
            }
            result=temp;
        }
    }
    return result;
}

class CustomVueAutoRouteWebapckPlugin extends VueAutoRouteWebpackPlugin {
    constructor(options) {
        super(options);
        this.routesMap2 = {};
    }
    touchRoute(route, parentRoute, pathItems, routeConfig) {
        let {
            rootComponent,
            indexComponent,
            useFileName
        } = this.options;
        let {
            _path,
            path: __path__,
            parentName,
            meta,
            name,
            lazy,
            redirect,
            alias,
            props
        } = routeConfig;
        routeConfig.lazy=true;
        // let _reoutes = parentRoute && parentRoute.children || route;
        let _reoutes = route;
        let pathItem = pathItems.shift();
        let components = {};
        if (this._isVue(pathItem)) {
            // let _path_ = `${_path}`;
            // let _path_ = lazy ? `${lazy}|lazy|${_path}` : _path;
            let _path_ = lazy ? `auto-${_reoutes.length}|lazy|${_path}` : _path;
            pathItem = pathItem.replace('.vue', '');
            components.default = _path_;
            if (pathItem === indexComponent) {
                if (parentRoute) {
                    parentRoute.name = name ? name : (useFileName && `${parentRoute.path}/${pathItem}`);
                    parentRoute.components = Object.assign(parentRoute.components, components);
                    parentRoute.meta = meta;
                    if (redirect !== undefined) parentRoute.redirect = redirect;
                    if (lazy !== undefined) parentRoute.lazy = lazy;
                    if (alias !== undefined) parentRoute.alias = alias;
                    if (props !== undefined) parentRoute.props = props;
                    this.routesMap[_path] = parentRoute;
                }
            } else {
                //重写路径生成逻辑
                var targetPath = __path__ || `${parentRoute ? parentRoute.path+'/'+pathItem : pathItem === rootComponent ? '/' : '/' + pathItem}`;
                targetPath = generateNewPath(targetPath);
                let _route_ = {
                    name: name ? name : (useFileName && pathItem),
                    // path: __path__ || `${parentRoute ? pathItem : pathItem === rootComponent ? '/' : '/' + pathItem}`,
                    path:targetPath,
                    components,
                    redirect,
                    alias,
                    props,
                    meta
                };
                if(parentName) {
                    _route_.parentName = parentName;
                }
                this.routesMap[_path] = _route_;
                this.routesMap2[_route_.name] = _route_;
                _reoutes.push(_route_);
            }
        } else if (this.options.ignoreDir != pathItem) {
            let _route = _reoutes.find(r => r.path === pathItem || r.path === '/' + pathItem);
            if (!_route) {
                _route = {
                    path: __path__ || `${parentRoute ? parentRoute.path+'/'+pathItem : '/' + pathItem}`,
                    redirect,
                    alias,
                    props,
                    children: [],
                    components: {}
                }
                _reoutes.push(_route);
            }
            // this.touchRoute(_route.children, _route, pathItems, routeConfig);
            this.touchRoute(_reoutes, _route, pathItems, routeConfig);
        }
    }
    buildRoute() {
        this.filesPath.forEach(path => {
            let routeConfig = this.files[path];
            this.pushOneRoute(routeConfig);
        });
        var removeIndexs = [];
        //子路由处理
        for(var route of this.routes) {
            if(!route.parentName) {
                continue;
            }
            var parentRoute = this.routesMap2[route.parentName];
            if(!parentRoute) {
                continue
            }
            if(!parentRoute.children) {
                parentRoute.children = [];
            }
            parentRoute.children.push(route);
            for(var i=0;i<this.routes.length;i++){
               if(route == this.routes[i]){
                   removeIndexs.unshift(i);
                   break;
               }
            }
        }
        if(removeIndexs.length>0) {
            //移除无用子路由数据
            for (var i = this.routes.length - 1, removeCount = 0; i >= 0&&removeCount<removeIndexs.length; i--) {
                if (i == removeIndexs[removeCount]) {
                    this.routes.splice(i, 1);
                    removeCount++;
                }
            }
        }
        //移除无用路由数据
        for (var i = this.routes.length - 1; i >= 0; i--) {
            var route = this.routes[i];
            if ((!route.children||route.children.length<=0)&&(!route.components||!route.components.default)&&!route.redirect) {
                this.routes.splice(i, 1);
            }
        }
        this.output();
    }
    output() {
        let routes = JSON.stringify(this.routes);
        //替换\为/,兼容windows路径
        var basePath = this.options.entry.replace(/\\/g,'/');
        routes = routes.replace(/"default":(".+?\.vue")/g, (v1, v2) => {
            let _v2 = v2.slice(1, -1).replace(/\\+/g, '/').split('|lazy|');
            if (_v2.length === 1) {
                return `default:require('${_v2[0].replace(basePath,'../views/')}').default`;
            } else if (_v2.length === 2) {
                let webpackChunkName = _v2[0] === 'true' ? '' : `/*webpackChunkName:"${_v2[0]}"*/`;
                return `default:()=>import(${webpackChunkName}"${_v2[1].replace(basePath,'../views/')}")`;
            } else {
                return `default:require('${v2.replace(basePath,'../views/')}').default`;
            }
        });
        fs.writeFileSync(this.options.output, `export default ${routes}`);
        this.checkDuplicate();
    }
}

module.exports = CustomVueAutoRouteWebapckPlugin;